<template>
  <div class="task-related-requirements-tab">
    <div class="tab-header">
      <div class="header-info">
        <span class="requirement-count">关联需求（{{ relatedRequirements.length }}）</span>
      </div>
      <div class="header-actions">
        <el-button
          type="primary"
          size="small"
          @click="handleAddRequirement"
        >
          <el-icon><Plus /></el-icon>
          添加需求
        </el-button>
      </div>
    </div>

    <div v-loading="loading" class="requirements-list">
      <el-table
        v-if="relatedRequirements.length > 0"
        :data="relatedRequirements"
        size="default"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="title" label="需求标题" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link 
              type="primary" 
              @click="handleViewRequirement(row.id)"
              :underline="false"
            >
              {{ row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="getStatusType(row.status)" 
              size="small"
            >
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="90">
          <template #default="{ row }">
            <el-tag 
              :type="getPriorityType(row.priority)" 
              size="small"
            >
              {{ getPriorityName(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="requirement_type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag size="small" type="info">
              {{ getTypeName(row.requirement_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="负责人" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <UserDisplay
              :user-id="row.assignee_id"
              :user-name="row.assignee_name"
              :show-avatar="true"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column label="报告人" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <UserDisplay
              :user-id="row.reporter_id"
              :user-name="row.reporter_name"
              :show-avatar="true"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.created_at) || '—' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleViewRequirement(row.id)"
            >
              查看
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="handleRemoveRequirement(row)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else description="暂无关联需求" :image-size="80" />
    </div>

    <!-- 需求选择对话框 -->
    <RequirementSelectorDialog
      v-model="requirementSelectorVisible"
      :project-id="projectId"
      @confirm="handleRequirementSelected"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import type { RequirementResponse } from '@/api/requirements'
import { formatDate } from '@/utils/date'
import { versionAPI, RelationType } from '@/api/version'
import { useRequirementStates } from '@/composables/useRequirementStates'
import { useRequirementOptions } from '@/composables/useRequirementOptions'
import UserDisplay from '@/components/ui/UserDisplay.vue'
import RequirementSelectorDialog from '@/components/version/RequirementSelectorDialog.vue'
import { taskAPI } from '@/api/task'

interface Props {
  taskId: string
  projectId?: string
  versionIds?: string[]
}

const props = defineProps<Props>()

const emit = defineEmits<{
  (event: 'requirement-updated'): void
}>()

const router = useRouter()
const loading = ref(false)
const relatedRequirements = ref<RequirementResponse[]>([])
const requirementSelectorVisible = ref(false)

const { getStateName, getStateColor, loadStates: loadRequirementStates } = useRequirementStates()
const { getPriorityName: getPriorityNameFromOptions, getTypeName: getTypeNameFromOptions, loadOptions: loadRequirementOptions } = useRequirementOptions()

const getStatusName = (status?: string) => {
  if (!status) return '未知'
  return getStateName(status)
}

const getStatusType = (status?: string) => {
  if (!status) return 'info'
  const color = getStateColor(status)
  // 根据颜色返回对应的 Element Plus tag type
  if (color.includes('green') || color.includes('success')) return 'success'
  if (color.includes('red') || color.includes('danger')) return 'danger'
  if (color.includes('orange') || color.includes('warning')) return 'warning'
  return 'info'
}

const getPriorityName = (priority?: string) => {
  if (!priority) return '未知'
  return getPriorityNameFromOptions(priority)
}

const getPriorityType = (priority?: string) => {
  if (!priority) return 'info'
  const code = priority.toLowerCase()
  if (code === 'high' || code === 'urgent') return 'danger'
  if (code === 'medium') return 'warning'
  return 'info'
}

const getTypeName = (type?: string) => {
  if (!type) return '未知'
  return getTypeNameFromOptions(type)
}

const fetchRelatedRequirements = async () => {
  if (!props.taskId) {
    relatedRequirements.value = []
    return
  }

  loading.value = true
  try {
    const allRequirements: RequirementResponse[] = []
    const requirementIds = new Set<string>()
    
    // 方式1: 直接从任务的 requirement_id 字段查询（直接关联）
    try {
      const taskResponse = await taskAPI.getTask(props.taskId)
      const task = taskResponse?.data || taskResponse
      if (task && task.requirement_id) {
        requirementIds.add(task.requirement_id)
      }
    } catch (error) {
      console.error('获取任务详情失败:', error)
    }
    
    // 方式2: 通过版本任务关联表查询关联的需求（通过版本关联）
    if (props.versionIds && props.versionIds.length > 0) {
      for (const versionId of props.versionIds) {
        try {
          // 获取版本关联的任务列表，包含 requirement_id 信息
          const taskRelations = await versionAPI.getVersionTasks(versionId, { skip: 0, limit: 100 })
          
          // 过滤出与当前任务ID匹配且有关联需求ID的记录
          const relatedRelations = taskRelations.filter(
            (relation: any) => relation.task_id === props.taskId && relation.requirement_id
          )
          
          // 收集需求ID
          for (const relation of relatedRelations) {
            if (relation.requirement_id && !requirementIds.has(relation.requirement_id)) {
              requirementIds.add(relation.requirement_id)
              
              // 如果有需求标题，直接使用；否则需要通过API获取详情
              if (relation.requirement_title) {
                allRequirements.push({
                  id: relation.requirement_id,
                  title: relation.requirement_title,
                  // 其他字段需要通过API获取，这里先使用基本信息
                } as RequirementResponse)
              }
            }
          }
        } catch (error) {
          console.error(`获取版本 ${versionId} 的任务关联失败:`, error)
        }
      }
    }
    
    // 如果有需求ID但没有完整信息，需要通过API获取详情
    if (requirementIds.size > 0) {
      try {
        const { getRequirementById } = await import('@/api/requirements')
        const requirementDetails = await Promise.allSettled(
          Array.from(requirementIds).map(id => getRequirementById(id))
        )
        
        for (const result of requirementDetails) {
          if (result.status === 'fulfilled' && result.value?.success && result.value?.data) {
            const requirement = result.value.data
            if (requirement && requirement.id) {
              const existingIndex = allRequirements.findIndex(req => req.id === requirement.id)
              if (existingIndex >= 0) {
                // 更新现有记录
                allRequirements[existingIndex] = requirement
              } else {
                // 添加新记录
                allRequirements.push(requirement)
              }
            }
          }
        }
      } catch (error) {
        console.error('获取需求详情失败:', error)
      }
    }
    
    // 去重
    const uniqueRequirements = Array.from(new Map(allRequirements.map(req => [req.id, req])).values())
    relatedRequirements.value = uniqueRequirements
  } catch (error) {
    console.error('获取关联需求失败:', error)
    ElMessage.error('获取关联需求失败')
    relatedRequirements.value = []
  } finally {
    loading.value = false
  }
}

const handleViewRequirement = (requirementId: string) => {
  router.push(`/requirements/${requirementId}`)
}

// 添加需求
const handleAddRequirement = () => {
  requirementSelectorVisible.value = true
}

// 处理需求选择
const handleRequirementSelected = async (requirements: RequirementResponse[]) => {
  if (!requirements.length || !props.taskId) return

  try {
    loading.value = true
    
    // 更新任务的 requirement_id 字段（直接关联）
    // 如果任务已经有关联需求，可以选择替换或添加到版本关联
    const requirementIds = requirements.map(r => r.id)
    
    // 方式1: 直接更新任务的 requirement_id（如果只有一个需求）
    if (requirementIds.length === 1) {
      try {
        await taskAPI.updateTask(props.taskId, { requirement_id: requirementIds[0] })
        ElMessage.success('需求关联成功')
      } catch (error) {
        console.error('更新任务需求关联失败:', error)
        // 如果直接更新失败，尝试通过版本关联
        if (props.versionIds && props.versionIds.length > 0) {
          await associateRequirementsViaVersion(requirementIds)
        } else {
          ElMessage.error('关联需求失败，请先关联版本')
          return
        }
      }
    } else {
      // 多个需求，通过版本关联
      if (props.versionIds && props.versionIds.length > 0) {
        await associateRequirementsViaVersion(requirementIds)
      } else {
        ElMessage.warning('多个需求需要先关联版本')
        // 仍然尝试更新第一个需求到任务字段
        try {
          await taskAPI.updateTask(props.taskId, { requirement_id: requirementIds[0] })
          ElMessage.success('已关联第一个需求到任务')
        } catch (error) {
          console.error('更新任务需求关联失败:', error)
          ElMessage.error('关联需求失败，请先关联版本')
          return
        }
      }
    }
    
    await fetchRelatedRequirements()
    emit('requirement-updated')
  } catch (error) {
    console.error('关联需求失败:', error)
    ElMessage.error('关联需求失败')
  } finally {
    loading.value = false
  }
}

// 通过版本关联需求
const associateRequirementsViaVersion = async (requirementIds: string[]) => {
  if (!props.versionIds || props.versionIds.length === 0) return
  
  const associatePromises = props.versionIds.map(versionId =>
    Promise.all(
      requirementIds.map(requirementId =>
        versionAPI.addTaskToVersion(versionId, {
          task_id: props.taskId,
          requirement_id: requirementId,
          relation_type: RelationType.INCLUDED
        }).catch(error => {
          console.error(`关联需求 ${requirementId} 到版本 ${versionId} 失败:`, error)
          return null
        })
      )
    )
  )
  
  await Promise.all(associatePromises)
  ElMessage.success('需求关联成功')
}

const handleRemoveRequirement = async (requirement: RequirementResponse) => {
  try {
    await ElMessageBox.confirm(
      `确定要移除需求"${requirement.title}"的关联吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    loading.value = true

    // 方式1: 如果任务的 requirement_id 就是当前需求，清空它
    try {
      const taskResponse = await taskAPI.getTask(props.taskId)
      const task = taskResponse?.data || taskResponse
      if (task && task.requirement_id === requirement.id) {
        await taskAPI.updateTask(props.taskId, { requirement_id: null })
        ElMessage.success('需求关联已移除')
        await fetchRelatedRequirements()
        emit('requirement-updated')
        return
      }
    } catch (error) {
      console.error('检查任务关联失败:', error)
    }

    // 方式2: 如果有版本ID，从版本关联中移除
    if (props.versionIds && props.versionIds.length > 0) {
      const removePromises = props.versionIds.map(versionId =>
        versionAPI.removeTaskFromVersion(versionId, props.taskId).catch(error => {
          console.error(`从版本 ${versionId} 移除任务关联失败:`, error)
          return null
        })
      )
      await Promise.all(removePromises)
      ElMessage.success('需求关联已移除')
    } else {
      ElMessage.success('需求关联已移除')
    }

    await fetchRelatedRequirements()
    emit('requirement-updated')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('移除需求关联失败:', error)
      ElMessage.error('移除需求关联失败')
    }
  } finally {
    loading.value = false
  }
}

watch(() => [props.taskId, props.versionIds, props.projectId], () => {
  fetchRelatedRequirements()
}, { immediate: true, deep: true })

onMounted(async () => {
  // 加载需求状态和选项数据
  await Promise.all([
    loadRequirementStates(),
    loadRequirementOptions()
  ])
  fetchRelatedRequirements()
})
</script>

<style scoped lang="scss">
.task-related-requirements-tab {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.requirement-count {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.requirements-list {
  min-height: 200px;
}
</style>


